const router = require('express').Router()
const request = require('request')
const fs = require('fs')
const path = require('path')
const Category = require('../models/Category')
const SubCategory = require('../models/SubCategory')
const Feed = require('../models/Feed')
const DetailModel = require('../models/Detail')
const ListItemModel = require('../models/ListItem')
const BannerModel = require('../models/Banner')

// 所有分类
router.get('/tabs', (req, res) => {
  request('http://www.xiongmaoyouxuan.com/api/tabs?sa=', {
    timeout: 15000,
  }, function (error, response, body) {
    const {data: {list}} = JSON.parse(body.toString())

    const result = []

    // const dir = path.join(__dirname, '../public/images/tabs')
    list.forEach(tab => {
      // const fileNameStartIndex = tab.imageUrl.lastIndexOf('/') + 1
      // const filename = tab.imageUrl.slice(fileNameStartIndex)
      // request(tab.imageUrl).on('error', () => {
      //   console.log('下载文件有误...')
      // }).pipe(fs.createWriteStream(path.join(dir, filename)))
      result.push({
        id: tab.id,
        name: tab.name,
        // imageUrl: '/images/tabs/' + filename,
        imageUrl: tab.imageUrl.replace('http://', 'https://'),
        note: tab.note
      })
    })

    Category
      .insertMany(result)
      .then(data => {
        res.json({
          data
        })
      })
      .catch(err => {
        res.json({
          error: true,
          message: err.message
        })
      })

    // console.error('error:', error) // Print the error if one occurred
    // console.log('statusCode:', response && response.statusCode) // Print the response status code if a response was received
    // console.log('body:', body) // Print the HTML for the Google homepage.
    // res.json({
    //   ...JSON.parse(body.toString())
    // })
  })
})

// 各子分类
router.get('/tab', (req, res) => {
  // const dir = path.join(__dirname, '../public/images/tab')
  const finished = []

  Category
    .find()
    .then(data => {
      data.slice(1).forEach((tab, index) => {
        finished[index] = false
        request('http://www.xiongmaoyouxuan.com/api/tab/' + tab.id, function(error, response, body) {
          const {data: {categories}} = JSON.parse(body.toString())
          const result = []
          categories.forEach(cate => {
            const listId = cate.url.slice(cate.url.lastIndexOf('=') + 1)
            const listType = cate.url.startsWith('youxuan://commoditylist') ? 'category' : 'column'
            const fileNameStartIndex = cate?.imageUrl?.lastIndexOf('/') + 1
            const filename = cate?.imageUrl?.slice(fileNameStartIndex)
            // request(cate.imageUrl).on('error', (err) => {
            //   console.log('下载文件有误...', err.message)
            // }).pipe(fs.createWriteStream(path.join(dir, filename)))
            finished[index] = true
  
            result.push({
              id: cate.id,
              title: cate.title,
              // imageUrl: '/images/tab/' + filename,
              imageUrl: cate.imageUrl.replace('http://', 'https://'),
              word: cate.word,
              parentCategoryId: tab.id,
              listId,
              listType,
            })
          })
          SubCategory
            .insertMany(result)
            .then(data => {
              finished[index] = true
            })
        })
      })
  
      const timer = setInterval(() => {
        const isFinished = finished.every(f => f)
        if (isFinished) {
          clearInterval(timer)
          res.json({
            code: 200,
            data: {
              message: '已经完成了'
            }
          })
        }
      }, 500)
    })
})

function getFeeds(tabId, finished, index) {
  const dir = path.join(__dirname, '../public/images/feeds')
  let start = -20

  function getData() {
    const random = Math.floor(Math.random() * 1000 + Math.random() * 200)
    start += 20
    // console.log('getData:', tabId)
    setTimeout(() => {
      const url = `http://www.xiongmaoyouxuan.com/api/tab/${tabId}/feeds?start=${start}`
      console.log('tabId:', tabId, ', url:', url)
      request(url, {timeout: 15000}, function(error, response, body) {
        if (error) {
          console.log('请求error:', error.message, item.id)
          return
        }
        
        try {
          // console.log('tabId:', tabId, ',body:', body)
          const {data: { list }} = JSON.parse(body.toString())
          const result = []
          list.forEach(({
            id,
            title,
            image,
            price,
            originPrice,
            saleNum,
            couponValue,
            isFreePostage,
          }) => {
            const fileNameStartIndex = image?.lastIndexOf('/') + 1
            const filename = image?.slice(fileNameStartIndex)
            // request(image).on('error', () => {
            //   console.log('下载文件有误...')
            // }).pipe(fs.createWriteStream(path.join(dir, filename)))

            result.push({
              id,
              title,
              // image: '/images/feeds/' + filename,
              image: image.replace('http://', 'https://'),
              price,
              originPrice,
              saleNum,
              couponValue,
              isFreePostage,
              tabId: tabId
            })
          })

          Feed
            .insertMany(result, {ordered: false})
            .then(() => {
              console.log('添加数据：', tabId)
              if (start >= 3000) {
                finished[index] = true
              }
            })
        } catch (error) {
          console.log('tabId 数据有异常:', tabId, ', start:', start)
          if (start >= 3000) {
            finished[index] = true
          }
        }
      })
    }, random)
    
    if (start >= 3000) {
      return
    }
    setTimeout(getData, Math.floor(Math.random() * 3000) + 1000)
  }

  getData()
}

// 推荐商品列表
router.get('/feeds', (req, res) => {
    const dir = path.join(__dirname, '../public/images/feeds')

    const finished = []

    Category
    .find({}, {_id: false, __v: false})
    .then(data => {
      data = [{}, {id: 1}]
      data.slice(1).forEach((item, index) => {
        finished[index] = false

        getFeeds(item.id, finished, index)

        // const random = Math.floor(Math.random() * 3000 + Math.random() * 2000)
        // setTimeout(() => {
        //   request(`http://www.xiongmaoyouxuan.com/api/tab/${item.id}/feeds?start=${start}`, function(error, response, body) {
        //     if (error) {
        //       console.log('请求error:', error.message, item.id)
        //       return
        //     }
        //     const {data: { list }} = JSON.parse(body.toString())
        //     const result = []
        //     list.forEach(({
        //       id,
        //       title,
        //       image,
        //       price,
        //       originPrice,
        //       saleNum,
        //       couponValue,
        //       isFreePostage,
        //     }) => {
        //       const fileNameStartIndex = image?.lastIndexOf('/') + 1
        //       const filename = image?.slice(fileNameStartIndex)
        //       request(image).on('error', () => {
        //         console.log('下载文件有误...')
        //       }).pipe(fs.createWriteStream(path.join(dir, filename)))

        //       result.push({
        //         id,
        //         title,
        //         image: '/images/feeds/' + filename,
        //         price,
        //         originPrice,
        //         saleNum,
        //         couponValue,
        //         isFreePostage,
        //         tabId: item.id
        //       })
        //     })

        //     Feed
        //       .insertMany(result, {ordered: false})
        //       .then(() => {
        //         finished[index] = true
        //       })
        //   })
        // }, random)

        
      })

      const timer = setInterval(() => {
        const isFinished = finished.every(f => f)
        if (isFinished) {
          clearInterval(timer)
          console.log('清除定时')
          res.json({
            code: 200,
            data: {
              message: '已经完成了'
            }
          })
        }
      }, 500)
    })
})

// 商品详情
router.get('/details', (req, res) => {
  let page = 10, pageSize = 1000

  function getData() {
    const finished = []
    page += 1
    Feed
      .find({}, {_id: false, __v: false})
      .limit(pageSize)
      .skip((page - 1) * pageSize)
      .then(data => {
        data
          .forEach(({id, image}, index) => {
            finished[index] = false
            const random = Math.floor(Math.random() * 1000)
            const url = 'http://www.xiongmaoyouxuan.com/api/detail?id=' + id
            DetailModel.find({id}).then(data => {
              if (data.length === 0) {
                setTimeout(() => {
                  request(url, {timeout: 15000}, (error, response, body) => {
                    console.log(index, ', url:', url)
                    try {
                      const {data: {detail: {
                        title,
                        price,
                        originPrice,
                        couponValue,
                        descContentList,
                        photo,
                      }, carouselList}} = JSON.parse(body.toString())
        
                      const detail = {
                        id,
                        image,
                        title,
                        price,
                        originPrice,
                        couponValue,
                        descContentList: descContentList.map(d => {
                          if (d.photo) {
                            return {
                              id: d.photo.id,
                              url: d.photo.url.replace('http://', 'https://')
                            }
                          }
                          return d
                        }),
                        photo: photo.map(p => {
                          return {
                            id: p.id,
                            url: p.url.replace('http://', 'https://'),
                          }
                        }),
                        carouselList,
                      }
        
                      DetailModel.insertMany([detail]).then(() => {
                        finished[index] = true
                      })
                    } catch (error) {
                      console.log('error::::::::::::', error.message)
                    }
                  })
                }, random)
              } else {
                finished[index] = true
              }
            })
          })
      })

    if (page >= 15) {
      return
    }
    setTimeout(getData, Math.floor(Math.random() * 3000) + 1000)
  }

  getData()
})

// 子分类列表数据
router.get('/sub/list', (req, res) => {
  SubCategory
    .find()
    .then(data => {
      data.forEach(item => {
        let start = 340
        function getData() {
          const url = `http://www.xiongmaoyouxuan.com/api/${item.listType}/${item.listId}/items?start=${start}`
          request(url, {timeout: 15000}, (error, response, body) => {
            console.log('request:::', url)
            try {
              const {data: {items: { list }}} = JSON.parse(body)
              list.forEach(({
                id,
                title,
                image,
                price,
                originPrice,
                saleNum,
                couponValue,
                isFreePostage,
              }) => {
                ListItemModel.find({id})
                  .then(data => {
                    if (data.length === 0) {
                      ListItemModel.insertMany([{
                        id,
                        title,
                        image: image.replace('http://', 'https://'),
                        price,
                        originPrice,
                        saleNum,
                        couponValue,
                        isFreePostage,
                        tabId: item.id
                      }])
                    }
                  })
              })
            } catch (error) {
              console.log('error:::::::', error.message, item.listId)
            }
          })
          start += 20

          if (start >= 500) {
            return
          }

          setTimeout(getData, 3000)
        }

        getData()
      })
    })
})

// 轮播图
router.get('/banners', (req, res) => {
  const url = 'https://music.163.com/store/api/product/ipbanner?type=1'
  request(url, {timeout: 15000}, (error, response, body) => {
    const {banners} = JSON.parse(body)
    const result = []
    banners.forEach(({id, picStr}) => {
      const filename = picStr.slice(picStr.lastIndexOf('/') + 1)
      request(picStr)
        .on('error', () => {
          console.log('下载文件错误...')
        })
        .pipe(fs.createWriteStream(path.join(__dirname, '../public/images/banners', filename)))
      result.push({
        id,
        image: '/images/banners/' + filename,
      })
    })
    BannerModel.insertMany(result).then(() => res.json('成功'))
  })
})

module.exports = router
